const tool = {}

// localStorage
tool.data = {
    set(table, settings) {
        const _set = JSON.stringify(settings)
        return localStorage.setItem(table, _set)
    },
    get(table) {
        let data = localStorage.getItem(table)
        try {
            data = JSON.parse(data)
        } catch (err) {
            return null
        }
        return data
    },
    remove(table) {
        return localStorage.removeItem(table)
    },

    clear() {
        return localStorage.clear()
    }
}

// 服务配置管理专用工具
tool.serviceConfig = {
    // 存储键名
    STORAGE_KEY: 'guard-app-services',

    // 获取所有服务配置
    getAll() {
        const configs = tool.data.get(this.STORAGE_KEY)
        return Array.isArray(configs) ? configs : this.getDefaultConfigs()
    },

    // 获取默认服务配置
    getDefaultConfigs() {
        return [
            /*{ name: 'nginx', displayName: 'Nginx', enabled: true },
            { name: 'mysql', displayName: 'MySQL', enabled: true },
            { name: 'redis', displayName: 'Redis', enabled: true }*/
        ]
    },

    // 根据服务名称获取配置
    getByName(name) {
        const configs = this.getAll()
        return configs.find(config => config.name === name) || null
    },

    // 添加服务配置
    addOrUpdate(config) {
        const configs = this.getAll()

        // 检查是否已存在
        if (configs.some(c => c.name === config.name)) {
            this.update(config)
        }

        configs.push(config)
        tool.data.set(this.STORAGE_KEY, configs)
        return true
    },

    // 更新服务配置
    update(config) {
        const configs = this.getAll()
        const index = configs.findIndex(c => c.name === config.name)

        if (index === -1) {
            throw new Error('服务不存在')
        }

        configs[index] = config
        tool.data.set(this.STORAGE_KEY, configs)
        return true
    },

    // 删除服务配置
    remove(name) {
        const configs = this.getAll()
        const index = configs.findIndex(c => c.name === name)

        if (index === -1) {
            throw new Error('服务不存在')
        }

        configs.splice(index, 1)
        tool.data.set(this.STORAGE_KEY, configs)
        return true
    },

    // 启用服务
    enable(name) {
        const config = this.getByName(name)
        if (config) {
            config.enabled = true
            return this.update(config)
        }
        throw new Error('服务不存在')
    },

    // 禁用服务
    disable(name) {
        const config = this.getByName(name)
        if (config) {
            config.enabled = false
            return this.update(config)
        }
        throw new Error('服务不存在')
    },

    // 获取启用的服务
    getEnabled() {
        return this.getAll().filter(config => config.enabled)
    },

    // 清空所有配置
    clear() {
        tool.data.remove(this.STORAGE_KEY)
    },

    // 导出配置
    export() {
        const configs = this.getAll()
        const exportData = {
            version: '1.0',
            timestamp: new Date().toISOString(),
            configs: configs
        }
        return JSON.stringify(exportData, null, 2)
    },

    // 导入配置
    import(data) {
        try {
            const importData = typeof data === 'string' ? JSON.parse(data) : data

            if (!importData.configs || !Array.isArray(importData.configs)) {
                throw new Error('无效的配置格式')
            }

            tool.data.set(this.STORAGE_KEY, importData.configs)
            return true
        } catch (error) {
            throw new Error('导入配置失败: ' + error.message)
        }
    }
}

// 通用数据管理工具
tool.storage = {
    // 设置数据
    set(key, value) {
        try {
            tool.data.set(key, value)
            return true
        } catch (error) {
            console.error('设置数据失败:', error)
            return false
        }
    },

    // 获取数据
    get(key, defaultValue = null) {
        const data = tool.data.get(key)
        return data !== null ? data : defaultValue
    },

    // 删除数据
    remove(key) {
        return tool.data.remove(key)
    },

    // 检查键是否存在
    has(key) {
        return localStorage.getItem(key) !== null
    },

    // 获取所有键
    keys() {
        return Object.keys(localStorage)
    },

    // 获取存储大小信息
    getStorageInfo() {
        let totalSize = 0
        const keys = []

        for (let i = 0; i < localStorage.length; i++) {
            const key = localStorage.key(i)
            const value = localStorage.getItem(key)
            const size = new Blob([key, value]).size
            totalSize += size
            keys.push({ key, size })
        }

        return {
            totalSize,
            keys: keys.sort((a, b) => b.size - a.size)
        }
    }
}

export default tool
